<template>
  <view class="content">
    <NavBar :title="title" :autoBack="false" id="nav">
      <template #left>
        <view class="navbar-left center" @click="goBack">
          <u-icon name="arrow-left" color="#007aff" size="34"></u-icon>
          <text class="c007aff">{{ lefttitle }}</text>
        </view>
      </template>
      <template #right>
        <view class="navbar-right c007aff center" @click="subInfo"> Done </view>
      </template>
    </NavBar>
    <view class="widths main" v-if="type === 'task'">
      <view class="flex tit">
        <view class="label">關鍵名稱</view>
        <view class="val">
          <u-input
            class="input"
            input-align="left"
            :show-confirmbar="false"
            v-model="task.title"
            maxlength="32"
            type="text"
            placeholder="ex.平面圖;3D示意圖..."
            placeholder-style="color:#e0e0e0;"
          />
        </view>
      </view>
      <view class="list">
        <view class="flex item">
          <view class="label">開始日期</view>
          <view
            class="val center startTme"
            :class="task.startTime === '請選擇日期' ? 'ce0' : 'c333'"
            @click="showSelectTime"
            >{{ task.startTime }}</view
          >
        </view>
        <view class="flex item">
          <view class="label">工作天數</view>
          <view class="val center workDay">
            <u-input
              class="input"
              input-align="right"
              :show-confirmbar="false"
              v-model="task.workdays"
              maxlength="4"
              type="text"
              placeholder="請輸入工作天數"
              placeholder-style="color:#e0e0e0;"
            />
          </view>
        </view>
        <view class="flex item">
          <view class="label">前置關鍵</view>
          <view class="val center startTme" @click="showTask">{{
            task.prekeyname
          }}</view>
        </view>
        <view class="flex item">
          <view class="label">工程費用</view>
          <view class="val center price">
            <u-input
              class="input"
              input-align="right"
              :show-confirmbar="false"
              v-model="task.price"
              maxlength="7"
              type="text"
              placeholder="請輸入工程費用"
              placeholder-style="color:#e0e0e0;"
            />
          </view>
        </view>
      </view>
    </view>
    <view class="widths main" v-if="type === 'list'">
      <view class="flex tit">
        <view class="label">摘要名稱</view>
        <view class="center val">
          <u-input
            class="input"
            input-align="left"
            :show-confirmbar="false"
            v-model="list.name"
            maxlength="32"
            type="text"
            placeholder="摘要 #1"
            placeholder-style="color:#e0e0e0;"
          />
        </view>
      </view>
      <view class="list task">
        <!-- <view class="flex item">
					<view class="label">開始日期</view>
					<view class="startTime center val" :class="list.startTime==='請選擇日期'?'ce0':'c333'" @click="showSelectTime">{{list.startTime}}</view>
				</view>
				<view class="flex item">
					<view class="label">結束日期</view>
					<view class="endTime center val" :class="list.endTime===''?'ce0':'c333'" @click="showSelectEndTime">{{list.endTime===''?'請選擇結束時間':list.endTime}}</view>
				</view> -->
        <!-- <view class="flex item">
					<view class="label">工程費用</view>
					<view class="val  price">
						<u-input class="input" input-align="right" :show-confirmbar="false" v-model="task.price" maxlength=7 type="text" placeholder="請輸入工程費用" placeholder-style="color:#e0e0e0;font-size:24rpx;" />
					</view>
					
				</view> -->
      </view>
    </view>
    <view class="widths main" v-if="type === 'case'">
      <view class="flex tit">
        <view class="label">專案名稱</view>
        <view class="val">
          <u-input
            class="input"
            input-align="left"
            :show-confirmbar="false"
            v-model="caseInfo.name"
            maxlength="32"
            type="text"
            placeholder="專案範例"
            placeholder-style="color:#e0e0e0;"
          />
        </view>
      </view>
      <view class="list">
        <view class="flex mb-8 item">所屬公司: {{ caseInfo.companyName }}</view>
        <view class="flex item">
          <view class="label">交件日期</view>
          <view
            class="startTme center val"
            :class="caseInfo.startTime === '請選擇日期' ? 'ce0' : 'c333'"
            @click="showSelectTime"
            >{{ caseInfo.startTime }}</view
          >
        </view>
        <!-- <view class="flex item">
					<view class="label">結束日期</view>
					<view class="endTime center val" :class="caseInfo.endTime===''?'ce0':'c333'" @click="showSelectEndTime">{{caseInfo.endTime===''?'請選擇結束時間':caseInfo.endTime}}</view>
				</view> -->
      </view>
    </view>
    <u-picker
      mode="time"
      start-year="2020"
      v-model="timeShow"
      @confirm="selectTime"
      confirm-text="確認"
      :default-time="defaultTime"
    ></u-picker>
    <u-picker
      mode="selector"
      v-model="taskShow"
      range-key="title"
      :range="taskList"
      @confirm="selectTask"
      confirm-text="確認"
      :default-selector="[taskIndex]"
    ></u-picker>

    <u-picker
      mode="time"
      start-year="2020"
      v-model="endTimeShow"
      @confirm="selectEndTime"
      confirm-text="確認"
      :default-time="defaultEndTime"
    ></u-picker>

    <Tabar></Tabar>
  </view>
</template>

<script>
import {
  addCase,
  addCasezy,
  addTasks,
  getCaseDetail,
  getCasezyDetail,
  getTaskDetail,
  getCaseAllTaskList,
} from '@/api/apis.js'
import NavBar from '@/component/NavBar'
import Tabar from '@/component/HomeTab'
import ZPaging from '@/node_modules/z-paging/components/z-paging/z-paging.vue'
export default {
  components: {
    NavBar,
    ZPaging,
    Tabar,
  },
  data() {
    return {
      curId: 0,
      type: '',
      title: '',
      lefttitle: '',
      task: {
        title: '',
        startTime: '請選擇日期',
        workdays: null,
        prekeyid: 0,
        prekeyname: '無',
        price: null,
        timestamp: '',
      },
      taskList: [
        {
          name: '任務1',
          id: 1,
        },
        {
          name: '任務2',
          id: 2,
        },
      ],
      taskShow: false,
      taskIndex: 0,
      list: {
        name: '',
        startTime: '',
        endTime: '',
        startTimeStamp: '',
        endTimeStamp: '',
      },
      caseInfo: {
        name: '',
        companyId: '',
        companyName: '',
        startTime: '',
        endTime: '',
        startTimeStamp: '',
        endTimeStamp: '',
      },
      info: {},
      timeShow: false,
      date: {
        year: 0,
        month: 0,
        day: 0,
        timestamp: '',
      },
      defaultTime: '',
      defaultEndTime: '',
      endTimeShow: false,
      model: 'add',
    }
  },
  onShow() {
    this.$nextTick(() => {
      if (uni.getStorageSync('islogin')) {
        this.init()
      }
    })
  },
  onLoad() {
    if (!uni.getStorageSync('islogin')) {
      this.$Toast('請先登錄')
      setTimeout(() => {
        this.toPage('Home')
      }, 1200)
    } else {
      const { id, type, item, model } = this.$Route.query
      if (!id && !type && !item && !model) {
        this.$Toast('數據錯誤')
        setTimeout(() => {
          this.toPage('Main')
        }, 1200)
      }
      if (!type) {
        this.$Toast('數據錯誤')
        setTimeout(() => {
          this.toPage('Main')
        }, 1200)
      } else {
        if (id) {
          this.curId = id
        }
        if (model) {
          this.model = model
        } else {
          this.model = 'add'
        }
        this.type = type
        if (this.type === 'case' && !model) {
          this.caseInfo.companyId = item.id
          this.caseInfo.companyName = item.name
        }
      }
    }
  },

  methods: {
    getCurDate() {
      var date = new Date(),
        year = date.getFullYear(), //年
        month = date.getMonth() + 1, //月
        day = date.getDate(), //日
        days = date.getDay()
      this.date.timestamp = Math.floor(
        Date.parse(year + '/' + month + '/' + day) / 1000
      )
      this.task.timestamp = this.date.timestamp
      this.date.year = year
      this.date.month = month
      this.date.day = day
    },
    timeTotimestamp(str) {
      return Math.floor(Date.parse(str) / 1000)
    },
    timeTostr(str) {
      let arr = str.split('/')
      let month = parseInt(arr[0])
      let day = parseInt(arr[1])
      let year = parseInt(arr[2])
      month = month > 9 ? month : '0' + month
      day = day > 9 ? day : '0' + day
      return year + '/' + month + '/' + day
    },
    async init() {
      this.getCurDate()
      this.list = {
        name: '',
        startTime: '',
        endTime: '',
      }
      this.defaultTime = ''
      this.defaultEndTime = ''
      this.defaultTime =
        this.date.year + '/' + this.date.month + '/' + this.date.day
      this.task.startTime =
        this.date.month + '/' + this.date.day + '/' + this.date.year
      this.list.startTime =
        this.date.month + '/' + this.date.day + '/' + this.date.year
      this.list.startTimeStamp = this.timeTotimestamp(
        this.date.year + '/' + this.date.month + '/' + this.date.day
      )
      this.caseInfo.startTime =
        this.date.month + '/' + this.date.day + '/' + this.date.year
      this.caseInfo.startTimeStamp = this.timeTotimestamp(
        this.date.year + '/' + this.date.month + '/' + this.date.day
      )
      this.defaultEndTime =
        this.date.month + '/' + this.date.day + '/' + this.date.year
      //list初始化
      let uid = uni.getStorageSync('uid')

      //拿取範例信息
      if (this.type === 'case') {
        this.lefttitle = '專案列表'
        this.title = this.model === 'edit' ? '修改專案' : '新增專案'
        //編輯模式
        if (this.model === 'edit') {
          getCaseDetail({ id: this.curId, uid })
            .then((res) => {
              this.caseInfo = res
              this.defaultEndTime = this.timeTostr(this.caseInfo.endTime)
            })
            .catch((err) => {
              this.$Errback(err.msg)
            })
        }
      } else if (this.type === 'task') {
        this.lefttitle = '摘要 #1'
        this.title = this.model === 'edit' ? '修改關鍵' : '新增關鍵'

        //獲取前置任務列表
       await getCaseAllTaskList({ id: this.curId, type: this.model, uid })
          .then((res) => {
            this.taskList = res
          })
          .catch((err) => {
            this.$Toast(err.msg)
          })
        //編輯模式
        if (this.model === 'edit') {
          getTaskDetail({ id: this.curId, uid })
            .then((res) => {
              this.task = res
              this.taskList.unshift({
                title: '無',
                id: '0',
                nextStart: res.startTime,
                nextTimestamp: res.timestamp,
                endtime: res.endtime,
                price: 0,
              })
            })
            .catch((err) => {
              this.$Errback(err.msg)
            })
        }
      } else if (this.type === 'list') {
        this.lefttitle = '專案範例'
        this.title = this.model === 'edit' ? '修改摘要' : '新增摘要'
        //編輯模式
        if (this.model === 'edit') {
          getCasezyDetail({ id: this.curId, uid })
            .then((res) => {
              this.list = res
              this.defaultEndTime = this.timeTostr(this.list.endTime)
            })
            .catch((err) => {
              this.$Errback(err.msg)
            })
        }
      } else {
        this.$Errback('數據錯誤')
      }
    },
    showSelectTime() {
      this.timeShow = true
    },
    selectTime(e) {
      if (this.type === 'task') {
        this.task.startTime =
          parseInt(e.month) + '/' + parseInt(e.day) + '/' + e.year
        this.task.timestamp = this.timeTotimestamp(
          e.year + '/' + parseInt(e.month) + '/' + parseInt(e.day)
        )
      } else if (this.type === 'list') {
        this.list.startTime =
          parseInt(e.month) + '/' + parseInt(e.day) + '/' + e.year
        this.list.startTimeStamp = this.timeTotimestamp(
          e.year + '/' + parseInt(e.month) + '/' + parseInt(e.day)
        )
      } else {
        this.caseInfo.startTime =
          parseInt(e.month) + '/' + parseInt(e.day) + '/' + e.year
        this.caseInfo.startTimeStamp = this.timeTotimestamp(
          e.year + '/' + parseInt(e.month) + '/' + parseInt(e.day)
        )
      }

      this.defaultTime = e.year + '/' + e.month + '/' + e.day
    },
    showSelectEndTime() {
      this.endTimeShow = true
    },
    selectEndTime(e) {
      if (this.type === 'list') {
        this.list.endTime =
          parseInt(e.month) + '/' + parseInt(e.day) + '/' + e.year
        this.list.endTimeStamp = this.timeTotimestamp(
          e.year + '/' + parseInt(e.month) + '/' + parseInt(e.day)
        )
      } else {
        this.caseInfo.endTime =
          parseInt(e.month) + '/' + parseInt(e.day) + '/' + e.year
        this.caseInfo.endTimeStamp = this.timeTotimestamp(
          e.year + '/' + parseInt(e.month) + '/' + parseInt(e.day)
        )
      }
      this.defaultEndTime = e.year + '/' + e.month + '/' + e.day
    },
    selectTask(e) {
      this.task.prekeyname = this.taskList[e].title
      this.task.prekeyid = this.taskList[e].id
      this.taskIndex = e[0]
      this.task.startTime = this.taskList[e].nextStart
      this.task.timestamp = this.taskList[e].nextTimestamp
    },
    showTask() {
      if (this.taskList.length > 0) {
        this.taskShow = true
      }
    },
    subInfo() {
      if (this.type === 'task') {
        if (!this.task.title) {
          this.$Toast('關鍵名稱不能為空')
          return false
        }
        if (!this.task.workdays) {
          this.$Toast('工作天數不能為空')
          return false
        }
        if (!/^[1-9]{1}\d{0,3}$/.test(this.task.workdays)) {
          this.$Toast('請輸入正確的工作天數')
          return false
        }
        // if(!this.task.price){
        // 	this.$Toast("工程費用不能為空")
        // 	return false;
        // }
        // let regex = /^\d+(\.\d{2})?$/;
        // let regex = /^\d*$/;
        // if(!regex.test(this.task.price)){
        // 	this.$Toast("請輸入正確的工程費用")
        // 	return false;
        // }
        let endTimeStamp =
          this.task.timestamp + (parseInt(this.task.workdays) - 1) * 86400
        // let endTime = this.$u.timeFormat(endTimeStamp, 'm/d/yyyy')
        let endTime = endTimeStamp

        let data = {
          zyid: this.curId,
          uid: uni.getStorageSync('uid'),
          title: this.task.title,
          start_time: this.task.timestamp,
          end_time: endTime,
          workdays: this.task.workdays,
          price: this.task.price,
          type: this.model,
        }
        if (this.task.prekeyid) {
          data.prekeyid = this.task.prekeyid
          data.prekeyname = this.task.prekeyname
        }
        // if(this.model==="edit") data.id=this.curId
        this.$Loading()
        addTasks(data)
          .then((res) => {
            uni.hideLoading()
            this.$Errback(res.msg)
          })
          .catch((err) => {
            uni.hideLoading()
            if (err.code === 102) {
              this.$ClearLogin(err.msg)
            } else {
              this.$Toast(err.msg)
            }
          })
      } else if (this.type === 'list') {
        if (!this.list.name) {
          this.$Toast('摘要名稱不能為空')
          return false
        }
        // if(!this.list.endTime){
        // 	this.$Toast("請選擇摘要結束日期")
        // 	return false;
        // }
        // if(this.list.endTimeStamp < this.list.startTimeStamp){
        // 	this.$Toast("結束日期不能小于開始日期")
        // 	return false;
        // }
        let data = {
          uid: uni.getStorageSync('uid'),
          title: this.list.name,
          cid: this.curId,
          // start_time:this.list.startTimeStamp,
          // end_time:this.list.endTimeStamp
          type: this.model,
        }
        if (this.model === 'edit') data.id = this.curId
        this.$Loading()
        addCasezy(data)
          .then((res) => {
            uni.hideLoading()
            this.$Errback(res.msg)
          })
          .catch((err) => {
            uni.hideLoading()
            if (err.code === 102) {
              this.$ClearLogin(err.msg)
            } else {
              this.$Toast(err.msg)
            }
          })
      } else if (this.type === 'case') {
        if (!this.caseInfo.name) {
          this.$Toast('專案名稱不能為空')
          return false
        }
        // if(!this.caseInfo.endTime){
        // 	this.$Toast("請選擇專案結束日期")
        // 	return false;
        // }
        // if(this.caseInfo.endTimeStamp < this.caseInfo.startTimeStamp){
        // 	this.$Toast("結束日期不能小于開始日期")
        // 	return false;
        // }
        let data = {
          uid: uni.getStorageSync('uid'),
          title: this.caseInfo.name,
          company_name: this.caseInfo.companyName,
          company_id: this.caseInfo.companyId,
          type: this.model,
          inputtime: this.caseInfo.startTimeStamp,
          // end_time:this.caseInfo.endTimeStamp
        }
        if (this.model === 'edit') data.id = this.curId
        this.$Loading()
        addCase(data)
          .then((res) => {
            uni.hideLoading()
            this.$Errback(res.msg)
          })
          .catch((err) => {
            uni.hideLoading()
            if (err.code === 102) {
              this.$ClearLogin(err.msg)
            } else {
              this.$Toast(err.msg)
            }
          })
      }
    },
    goBack() {
      uni.navigateBack(-1)
    },
    toPage(name, params = {}) {
      this.$navi({
        route: {
          name,
          params,
        },
      })
    },
  },
}
</script>

<style lang="scss">
.content {
  min-height: 100vh;
}
.totalprogress {
  height: 228rpx;
  background-color: #ffd33b;
  padding: 0 4%;
  padding-top: 88rpx;
  .label {
    width: 140rpx;
    flex-shrink: 0;
  }
  .val {
    width: calc(100% - 160rpx);

    .pro {
      width: calc(100% - 70rpx);
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      top: 4rpx;
    }
    .txt {
      width: 70rpx;
      flex-shrink: 0;
    }
  }
}
.main {
  padding-top: 88rpx;
  .tit {
    width: 70%;
    margin: 20rpx auto 30rpx;
    justify-content: flex-start;
    .label {
      width: 120rpx;
      margin-right: 20rpx;
    }
    .val {
      width: calc(100% - 140rpx);
    }
  }
  .list {
    /deep/ .u-btn-text {
      color: #fff !important;
    }
    .item {
      // padding: 4rpx 0;
      .val {
        height: 60rpx;
      }
    }
    &.task {
      .item {
        align-items: center;
      }
    }
  }
}
</style>
